/**
 * 
 */
package com.community.demo.datamodel;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import java.util.Comparator;

import org.apache.commons.beanutils.BeanUtils;
import org.primefaces.model.SortOrder;

public class LazySorter implements Comparator<Object> {

    private String sortField;
    
    private SortOrder sortOrder;
    
    public LazySorter(String sortField, SortOrder sortOrder) {
        this.sortField = sortField;
        this.sortOrder = sortOrder;
    }
    
    @SuppressWarnings("unchecked")
    public int compare(Object object1, Object object2) {
        try {
        	Object value1 = BeanUtils.getProperty(object1, this.sortField);
        	Object value2 = BeanUtils.getProperty(object2, this.sortField);

            int value = ((Comparable<Object>) value1).compareTo(value2);
            
            return SortOrder.ASCENDING.equals(sortOrder) ? value : -1 * value;
        } catch(Exception e) {
            throw new RuntimeException();
        }
    }
}
